package hsb.ruoyi.common.config.security;

import com.usthe.sureness.matcher.PathTreeProvider;
import hsb.ruoyi.common.core.domain.entity.RolePermItem;
import hsb.ruoyi.system.service.ISysMenuService;

import javax.enterprise.inject.spi.CDI;
import java.util.*;

/**
 * @author 胡帅博
 * @date 2023/1/2 15:07
 */
public class MyPathTreeProvider implements PathTreeProvider {


    ISysMenuService sysMenuService;


    private volatile boolean isFirst = true;

    @Override
    public Set<String> providePathData() {
        Set<String> rules = new HashSet<>();
        sysMenuService = CDI.current().select(ISysMenuService.class).get();
        List<RolePermItem> permItems = sysMenuService.selectAllRolePerms();

        Map<String, Set<String>> permMap = new HashMap<>(permItems.size());
        for (RolePermItem permItem : permItems) {
            String perms = permItem.perms;
            perms = "/" + perms.replace(":", "/");
            Set<String> roles = permMap.computeIfAbsent(perms, k -> new HashSet<String>());
            if (permItem.roleKey == null) {
                roles.add("*");
            } else {
                roles.add(permItem.roleKey);
                roles.add("admin");
            }

        }
        permMap.forEach((perms, roles) -> {
            String roleKeys = String.join(",", roles);
            rules.add(perms + "===*===[" + roleKeys + "]");
        });
        rules.add("/**===*===[**]"); //角色使用** 代表匹配任意角色,只要登陆就行
       //rules.add("/**===*===[admin]");  //这个是用来让其他没有配置的路径都可以被admin角色访问
        return rules;
    }

    @Override
    public Set<String> provideExcludedResource() {
        Set<String> rules = new HashSet<>();
        // "/loginApi", "/app/weixinlogin","/register","/app/pwdLogin", "/captchaImage"
        rules.add("/test/**===*");
        rules.add("/loginApi===*");
        rules.add("/logout===*");
        rules.add("/app/weixinlogin===*");
        rules.add("/app/register===*");
        rules.add("/app/pwdLogin===*");
        rules.add("/captchaImage===*");
        return rules;
    }


}
